import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  Button,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  ListItemSecondaryAction,
  IconButton,
  Divider,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Collapse,
  CircularProgress,
} from '@mui/material';
import {
  Folder as FolderIcon,
  FolderOpen as FolderOpenIcon,
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  ExpandLess,
  ExpandMore,
} from '@mui/icons-material';
import axios from 'axios';

const CategoryPage = () => {
  const navigate = useNavigate();
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(true);
  const [expandedCategories, setExpandedCategories] = useState({});
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [categoryToDelete, setCategoryToDelete] = useState(null);

  useEffect(() => {
    fetchCategories();
  }, []);

  const fetchCategories = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/api/category');
      setCategories(response.data);
    } catch (error) {
      console.error('获取分类失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleCategoryClick = (categoryId) => {
    setExpandedCategories(prev => ({
      ...prev,
      [categoryId]: !prev[categoryId]
    }));
  };

  const handleAddCategory = () => {
    navigate('/category/new');
  };

  const handleEditCategory = (e, categoryId) => {
    e.stopPropagation();
    navigate(`/category/edit/${categoryId}`);
  };

  const handleDeleteClick = (e, category) => {
    e.stopPropagation();
    setCategoryToDelete(category);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!categoryToDelete) return;

    try {
      await axios.delete(`/api/category/${categoryToDelete.id}`);
      fetchCategories();
    } catch (error) {
      console.error('删除分类失败:', error);
      alert('删除失败，请稍后重试');
    } finally {
      setDeleteDialogOpen(false);
      setCategoryToDelete(null);
    }
  };

  const handleDeleteCancel = () => {
    setDeleteDialogOpen(false);
    setCategoryToDelete(null);
  };

  const handleViewCategory = (e, categoryId) => {
    e.stopPropagation();
    navigate(`/category/${categoryId}`);
  };

  const renderCategoryTree = (category) => {
    const isExpanded = expandedCategories[category.id];
    const hasChildren = category.children && category.children.length > 0;

    return (
      <React.Fragment key={category.id}>
        <ListItem 
          button 
          onClick={() => hasChildren ? handleCategoryClick(category.id) : handleViewCategory(null, category.id)}
        >
          <ListItemIcon>
            {hasChildren ? 
              (isExpanded ? <FolderOpenIcon /> : <FolderIcon />) : 
              <FolderIcon />}
          </ListItemIcon>
          <ListItemText 
            primary={category.name} 
            secondary={category.description || '无描述'} 
          />
          {hasChildren && (
            <Box sx={{ mr: 2 }}>
              {isExpanded ? <ExpandLess /> : <ExpandMore />}
            </Box>
          )}
          <ListItemSecondaryAction>
            <IconButton edge="end" onClick={(e) => handleViewCategory(e, category.id)}>
              <FolderOpenIcon fontSize="small" />
            </IconButton>
            <IconButton edge="end" onClick={(e) => handleEditCategory(e, category.id)}>
              <EditIcon fontSize="small" />
            </IconButton>
            <IconButton edge="end" onClick={(e) => handleDeleteClick(e, category)}>
              <DeleteIcon fontSize="small" />
            </IconButton>
          </ListItemSecondaryAction>
        </ListItem>
        {hasChildren && (
          <Collapse in={isExpanded} timeout="auto" unmountOnExit>
            <List component="div" disablePadding sx={{ pl: 4 }}>
              {category.children.map(child => renderCategoryTree(child))}
            </List>
          </Collapse>
        )}
      </React.Fragment>
    );
  };

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Paper elevation={0} sx={{ p: 3, mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Typography variant="h4" component="h1">
            分类管理
          </Typography>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={handleAddCategory}
          >
            新建分类
          </Button>
        </Box>

        <Divider sx={{ mb: 2 }} />

        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
            <CircularProgress />
          </Box>
        ) : (
          <List>
            {categories.length > 0 ? (
              categories.map(category => renderCategoryTree(category))
            ) : (
              <ListItem>
                <ListItemText primary="暂无分类" secondary="点击右上角按钮创建新分类" />
              </ListItem>
            )}
          </List>
        )}
      </Paper>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={handleDeleteCancel}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <DialogContentText>
            确定要删除分类 "{categoryToDelete?.name}" 吗？此操作不可撤销，且会删除该分类下的所有子分类。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleDeleteCancel}>取消</Button>
          <Button onClick={handleDeleteConfirm} color="error" autoFocus>
            删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default CategoryPage;